const express = require('express');
const bodyParser = require('body-parser');
const uploader = require('express-fileupload');
const { 
    extname,
    resolve
} = require('path');
const {
    existsSync,
    appendFileSync,
    writeFileSync
} = require('fs');
const app = express();
const PORT = 8000;

app.use(uploader())
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use('/', express.static('upload_temp'));
app.all('*', (req, res, next) => {
    res.header("Access-Control-Allow-Origin", "*");
	res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
	res.header("Access-Control-Allow-Headers", "X-Requested-With");
	res.header('Access-Control-Allow-Headers', ['mytoken','Content-Type']);
    next()
})

app.post('/upload-video', (req, res) => {
    console.log('req', req);
    const { name, type, size, fileName, uploadedSize } = req.body;
    const { file } = req.files;

    if (!file) {
        res.send({
            code: 1001,
            msg: '没有文件'
        })
        return;
    }
    
    const filename = fileName + extname(name);
    const filePath = resolve(__dirname, './upload_temp/' + filename);

    if (uploadedSize !== '0') {
        if (!existsSync(filePath)) {
            res.send({
                code: 1002,
                msg: '储存目录没有该文件！'
            })
            return;
        }

        appendFileSync(filePath, file.data);
        res.send({
            code: 0,
            msg: '成功',
            video_url: 'http://localhost:8000/' + filename
        })
        return;
    }

    writeFileSync(filePath, file.data);
    res.send({
        code: 0,
        msg: '成功'
    })
})

app.listen(PORT, () => {
    console.log('Server is Running in ' + PORT)
});